package com.xsir.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xsir.common.Result;
import com.xsir.entity.User;
import com.xsir.service.IUserService;
import io.jsonwebtoken.lang.Collections;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xsir
 * @date 2020/9/20
 */
@RestController
@RequestMapping("/admin")
@Api(value = "admin", description = "后台管理的api接口")
public class AdminController {
    @Resource
    private IUserService userService;
    
    /**
     * 管理员登录
     *
     * @param account  账号
     * @param password 密码
     * @return
     */
    @ApiOperation(value = "管理员登陆接口", httpMethod = "POST")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "account", value = "账号", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map<String, Object> login(String account, String password) {
        String token = userService.login(account, password, 1);
        Map<String, Object> data = new HashMap<>(4);
        data.put("token", token);
        data.put("code", 200);
        data.put("msg", "登录成功！");
        return data;
    }
    
    /**
     * 分页查询用户
     *
     * @param page 分页对象
     * @return
     */
    @ApiOperation(value = "分页查询用户列表", httpMethod = "GET")
    @RequiresRoles("admin")
    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public Result users(Page<User> page) {
        Page<User> userPage = userService.page(page);
        List<User> userList = userPage.getRecords();
        long total = userPage.getTotal();
        Map<String, Object> data = new HashMap<>(2);
        data.put("list", userList);
        data.put("total", total);
        return Result.ok(data);
    }
    
    /**
     * 批量添加用户
     *
     * @param userList 用户列表
     * @return
     */
    @ApiOperation(value = "批量添加用户", httpMethod = "POST")
    @ApiImplicitParam(value = "用户列表", dataTypeClass = List.class)
    @ApiResponses(value = {
            @ApiResponse(code = 400, message = "参数不正确"),
            @ApiResponse(code = 200, message = "添加成功")
    })
    @RequiresRoles("admin")
    @RequestMapping(value = "/users/list", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public Result insertBatch(@RequestBody List<User> userList) {
        if (Collections.isEmpty(userList)) {
            return Result.error("参数不正确", 400);
        }
        userService.insertBatch(userList);
        return Result.ok("添加成功");
    }
}
